<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/24 13:57
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Cancel2_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (empty($params['userId']) || empty($params['sn'])) {
                $send['error'] = '参数错误';
                break;
            }

            if (!$this->doCancel($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $send['state'] = true;
            $send['data'] = [
                'msg' => '订单取消成功'
            ];

        } while(false);
        $this->output->send($send);
    }

    /**
     * 执行取消订单
     * @param array $params
     * @return bool
     */
    private function doCancel(Array $params)
    {
        $orderInfo = $this->getOrder($params['sn']);
        if (empty($orderInfo)) {
            $this->setError('订单不存在');
            return false;
        }

        foreach ($orderInfo as $info) {
            if (!in_array($info['status'], array('Unpaid'))) {
                $this->setError('该订单状态已无法取消');
                return false;
            }
        }

        $db = clone($this->db);
        $db->where('uuid', $params['sn']);
        $db->update('user_order', array('status' => 'Cancel'));
        if ($db->affected_rows()) {
            return true;
        }

        $this->setError('订单取消失败');
        return false;
    }

    /**
     * 获取订单
     * @param int $orderId
     * @return bool
     */
    private function getOrder($orderId = 0)
    {
        if (empty($orderId)) {
            return false;
        }

        $db = clone($this->db);
        $q = $db->get_where('user_order', array('uuid' => $orderId));
        return $q->result_array();
    }
}